package cn.edu.zjitc.servlet.code.ex03;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "ConfigContextServlet", urlPatterns = "/configContext",initParams = {
        @WebInitParam(name = "myParam", value = "myValue")
})
public class ConfigContextServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        String param = config.getInitParameter("myParam");
        System.out.println("初始化参数：" + param);

        // 获取 ServletContext
        ServletContext context = config.getServletContext();
        String realPath = context.getRealPath("/");
        System.out.println("应用真实路径：" + realPath);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = getServletContext();
        String contextPath = context.getContextPath();
        resp.setContentType("text/plain;charset=UTF-8");
        resp.getWriter().write("应用上下文路径：" + contextPath);
    }
}